/**
 * Created by Tuffy on 16/1/18.
 */
'use strict';

angular.module('starter.controllers')

.controller('WorkCtrl', ['$scope','$rootScope','$state','$timeout','ionicMaterialMotion', 'ionicMaterialInk','WorkService','$filter',
    function($scope,$rootScope, $state,$timeout,ionicMaterialMotion, ionicMaterialInk,WorkService,$filter) {

    $scope.tabs = [{
        id:'2',
        name:'待办',
        dataList:{
            type:2,
            search: {
                value:'',
                filter:{},
                doAct:function(){
                    var _this =  $scope.tabs[0].dataList;
                    if(this.timer){
                        $timeout.cancel(this.timer);
                    }
                    this.timer = $timeout(function(){
                        _this.data = [];
                        _this.loadData();
                    },500);
                }
            },
            page: {
                pageNum:1,
                pageSize:20,
                total:0
            },
            loaded:false,
            data:[],
            loadData:function(okFunc){
                $scope.loadData($scope.tabs[0].dataList,okFunc);
            },
            moreDataCanBeLoaded:false,
            loadMore:function(){
                this.page.pageNum++;
                this.loadData();
            },
            refresh:function(){
                var _this = this;
                _this.page.pageNum = 1;
                _this.loadData(function(){
                    _this.data = [];
                });
            }
        }
    },{
        id:'1',
        name:'完成',
        dataList:{
            type:1,
            search: {
                value:'',
                filter:{},
                doAct:function(){
                    var _this =  $scope.tabs[1].dataList;
                    if(this.timer){
                        $timeout.cancel(this.timer);
                    }
                    this.timer = $timeout(function(){
                        _this.data = [];
                        _this.loadData();
                    },500);
                }
            },
            page: {
                pageNum:1,
                pageSize:20,
                total:0
            },
            loaded:false,
            data:[],
            loadData:function(okFunc){
                $scope.loadData($scope.tabs[1].dataList,okFunc);
            },
            moreDataCanBeLoaded:false,
            loadMore:function(){
                this.page.pageNum++;
                this.loadData();
            },
            refresh:function(){
                var _this = this;
                _this.page.pageNum = 1;
                _this.loadData(function(){
                    _this.data = [];
                });
            }
        }
    }];

    $scope.loadData = function(_this,okFunc){
        var isFirstPage = function() {
            if (_this.page.pageNum === 1) {
                return '';
            }
            return _this.data.length > 0 ? $filter('date')(_this.data[_this.data.length-1].createTime,'yyyyMMddhhmmss') : '';
        };
        var params = {
                createTime: isFirstPage(),
                pageSize:_this.page.pageSize,
                isComplete:_this.type
            };
        _this.loaded = false;
        for(var key in _this.search.filter){
            params[key] = _this.search.filter[key];
        }
        WorkService.findList(params)
            .success(function(res){
                if(res.success){
                    if(typeof (okFunc) == 'function'){
                        okFunc();
                    }
                    _this.data = _this.data.concat(res.attribute.rows);
                    if(res.attribute.rows.length<_this.page.pageSize){
                        _this.moreDataCanBeLoaded = false;
                    }
                }else{
                    console.log('没有最新数据');
                }
            }).error(function(error){
            _this.page.total = 0;
            console.log(error);
        }).finally(function(){
            _this.loaded = true;
            if(_this.data.length==0){
                _this.moreDataCanBeLoaded = false;
            }
            $scope.$broadcast('scroll.refreshComplete');
            $scope.$broadcast('scroll.infiniteScrollComplete');
            $timeout(function() {
                ionicMaterialMotion.blinds();
            }, 200);

            $timeout(function() {
                ionicMaterialInk.displayEffect();
            }, 1000);
        });
    };

    $scope.noData = "暂无任务";
    $scope.onTabChange = function(index){
        $scope.active =  index;
        var _this = $scope.tabs[index].dataList,
            loaded = _this.loaded;
        /*if($scope.tabs[index].id == 1){
            //已完成
            $scope.noData = "暂无任务";
        }else{
            $scope.noData = "任务全部完成，太棒了！";
        }*/
        if(!loaded){
            _this.moreDataCanBeLoaded = true;
            _this.loadData();
        }
    };
    //监听任务完成事件
    $rootScope.$on('TASK_COMPLETE',function(event,taskId){
        for(var i in $scope.tabs[0].dataList.data){
            var item = $scope.tabs[0].dataList.data[i];
            if(item.id == taskId){
                item.isComplete = 1;
            }
        }
    });
    $scope.onTabChange(0);
}])
.controller('WorkDetailCtrl', ['$scope','$rootScope', '$state', 'WorkService', '$cordovaToast',
    function($scope,$rootScope, $state, WorkService,$cordovaToast) {

    var taskId = $state.params.id,
        loadData = function(){
            WorkService.findById(taskId)
                .success(function(res){
                    if(res.success){
                        $scope.task = res.attribute;
                    }else{
                        $cordovaToast.showShortBottom('获取任务失败');
                    }
                }).error(function(error){
                    console.log(error);
                }).finally(function(){

                });
        },doComplete = function(){
            WorkService.complete(taskId)
                .success(function(res){
                    if(res.success){
                        $cordovaToast.showShortBottom('操作成功');
                        $rootScope.$broadcast('TASK_COMPLETE',taskId);
                        $scope.$ionicGoBack();
                    }else{
                        $cordovaToast.showShortBottom('操作失败');
                    }
                }).error(function(error){
                    console.log(error);
                }).finally(function(){

                });
        };

    $scope.task = {};
    $scope.doComplete = function(){
        doComplete();
    };

    if(taskId){
        loadData();
    }
}])
.service('WorkService',['CrmHttp','$rootScope',function(CrmHttp,$rootScope){
    var url = '/crm/user-task/';
    return {
        /**
         * 全部任务
         * @param params
         * @returns {*}
         */
        findList: function (params) {
            var act = 'find-list-by-receive';
            params['receiveUserId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 获取单个任务
         * @param params
         * @returns {*}
         */
        findById: function (taskId) {
            var act = 'find-receive-task',
                params = {};
            params['id'] = taskId;
            return CrmHttp.post(url + act, params);
        },
        /**
         * 完成任务
         * @param taskId
         * @returns {*}
         */
        complete: function(taskId){
            var act = 'update-receive-complete',
            params = {};
            params['id'] = taskId;
            return CrmHttp.post(url + act, params);

        }
    };
}]);